package com.yunshan.order.service.impl;

import com.yunshan.common.annotation.DataScope;
import com.yunshan.common.utils.DateUtils;
import com.yunshan.common.utils.SecurityUtils;
import com.yunshan.common.utils.StringUtils;
import com.yunshan.common.utils.uuid.UUID;
import com.yunshan.member.domain.MemberSubCardInfo;
import com.yunshan.member.domain.MemberUserInfo;
import com.yunshan.member.domain.ResultMember;
import com.yunshan.member.service.IMemberSubCardInfoService;
import com.yunshan.member.service.IMemberUserInfoService;
import com.yunshan.mp.domain.MpServeInfo;
import com.yunshan.mp.service.IMpServeInfoService;
import com.yunshan.order.domain.OrderConsumeRecord;
import com.yunshan.order.domain.OrderUniVo;
import com.yunshan.order.mapper.OrderConsumeRecordMapper;
import com.yunshan.order.service.IOrderConsumeRecordService;
import com.yunshan.welfare.domain.*;
import com.yunshan.welfare.service.IWelfareCouponRecordService;
import com.yunshan.welfare.service.IWelfareCouponService;
import com.yunshan.welfare.service.IWelfareGiftContentService;
import com.yunshan.welfare.service.IWelfareGiftRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import static com.yunshan.common.core.domain.AjaxResult.error;

/**
 * 消费订单Service业务层处理
 *
 * @author yunshan
 * @date 2025-01-20
 */
@Service
public class OrderConsumeRecordServiceImpl implements IOrderConsumeRecordService
{
    @Autowired
    private OrderConsumeRecordMapper orderConsumeRecordMapper;
    @Autowired
    private IMemberUserInfoService memberUserInfoService;
    @Autowired
    private IMpServeInfoService mpServeInfoService;
    @Autowired
    private IMemberSubCardInfoService memberSubCardInfoService;
    @Autowired
    private IWelfareGiftRecordService welfareGiftRecordService;
    @Autowired
    private IWelfareCouponRecordService welfareCouponRecordService;
    @Autowired
    private IWelfareCouponService welfareCouponService;
    @Autowired
    private IWelfareGiftContentService welfareGiftContentService;

    /**
     * 查询消费订单
     *
     * @param id 消费订单主键
     * @return 消费订单
     */
    @Override
    public OrderConsumeRecord selectOrderConsumeRecordById(Long id)
    {
        OrderConsumeRecord orderConsumeRecord = orderConsumeRecordMapper.selectOrderConsumeRecordById(id);
        if (orderConsumeRecord.getCardType() == 1){
            ResultMember memberUserInfo = memberUserInfoService.selectResultMember(orderConsumeRecord.getMemberId());
            if (memberUserInfo != null){
                orderConsumeRecord.setResultMember(memberUserInfo);
            }
        }else {
            ResultMember memberSubCardInfo = memberSubCardInfoService.selectResultMember(orderConsumeRecord.getMemberId());
            if (memberSubCardInfo != null){
                orderConsumeRecord.setResultMember(memberSubCardInfo);
            }
        }
        return orderConsumeRecord;
    }

    /**
     * 查询消费订单列表
     *
     * @param orderConsumeRecord 消费订单
     * @return 消费订单
     */
    @Override
    @DataScope(deptAlias = "order_consume_record")
    public List<OrderConsumeRecord> selectOrderConsumeRecordList(OrderConsumeRecord orderConsumeRecord)
    {
        return orderConsumeRecordMapper.selectOrderConsumeRecordList(orderConsumeRecord);
    }

    /**
     * 新增消费订单
     *
     * @param orderConsumeRecord 消费订单
     * @return 结果
     */
    @Override
    public int insertOrderConsumeRecord(OrderConsumeRecord orderConsumeRecord)
    {
        try {
            //通过手机号查询用户信息
            MemberUserInfo memberUserInfo = memberUserInfoService.selectMemberUserInfoById(orderConsumeRecord.getMemberId());
            if (memberUserInfo == null) {
                MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectMemberSubCardInfoById(orderConsumeRecord.getMemberId());
                if (memberSubCardInfo == null) {
                    throw new RuntimeException("未查询到会员信息");
                } else {
                    orderConsumeRecord.setCardType(2);
                    memberUserInfo = memberUserInfoService.selectMemberUserInfoById(memberSubCardInfo.getMemberId());
                }
            } else {
                if ("4".equals(memberUserInfo.getMemberType())) {
                    throw new RuntimeException("临时会籍暂不支持余额消费");
                }

                orderConsumeRecord.setCardType(1);
                orderConsumeRecord.setMemberId(memberUserInfo.getId());
            }


            //判断是否余额消费，余额消费扣减金额
            switch (orderConsumeRecord.getPayType()) {
                case 1:
                    //通过服务id查询服务信息
                    MpServeInfo mpServeInfo = mpServeInfoService.selectMpServeInfoById(orderConsumeRecord.getServeId());
                    if (mpServeInfo == null) {
                        throw new RuntimeException("服务项目不存在");
                    }
                    if (orderConsumeRecord.getAmount() == null) {
                        orderConsumeRecord.setAmount(mpServeInfo.getPrice());
                    }

                    //如果是餐饮项目，金额=金额*人数
                    if ("1".equals(orderConsumeRecord.getServeType()) && orderConsumeRecord.getNum() != null) {
                        orderConsumeRecord.setAmount(orderConsumeRecord.getAmount().multiply(new BigDecimal(orderConsumeRecord.getNum())));
                    }

                    //扣减余额
                    synchronized (this) {
                        int i = memberUserInfoService.updateMemberBalance(memberUserInfo.getId(), orderConsumeRecord.getAmount());
                        if (i < 1) {
                            throw new RuntimeException("余额不足，请先充值！");
                        }
                    }

                    if (orderConsumeRecord.getCardType() == 2){
                        memberSubCardInfoService.updateMemberSubTotalAmount(orderConsumeRecord.getMemberId(),orderConsumeRecord.getAmount());
                    }

                    orderConsumeRecord.setServeType(mpServeInfo.getServeType());
                    orderConsumeRecord.setServeName(mpServeInfo.getName());
                    break;

                case 2:
                    //礼包消费
                    if (orderConsumeRecord.getGiftRecordId() != null) {

                        //核销不需要更新礼包状态
                        if (StringUtils.isEmpty(orderConsumeRecord.getOrderNum())) {
                            //通过礼包内容id查询出礼包记录id
                            WelfareGiftRecord giftRecord = welfareGiftRecordService.selectWelfareGiftRecordById(orderConsumeRecord.getGiftRecordId());

                            if(giftRecord != null && giftRecord.getStatus() == 0) {
                                WelfareGiftContent welfareGiftContent = welfareGiftContentService.selectWelfareGiftContentById(giftRecord.getGiftContentId());

                                giftRecord.setStatus(1);
                                orderConsumeRecord.setServeName(welfareGiftContent.getContentName());
                                orderConsumeRecord.setServeType(welfareGiftContent.getServeType());

                                int i = welfareGiftRecordService.updateWelfareGiftRecord(giftRecord);

                                if (i < 1) {
                                    throw new RuntimeException("核销礼包失败");
                                }
                            }else {
                                throw new RuntimeException("核销礼包失败，请检查礼包状态");
                            }
                        }
                    } else {
                        throw new RuntimeException("请选择正确的核销方式");
                    }
                    break;

                case 3:
                    //优惠券消费
                    if (orderConsumeRecord.getCouponRecordId() != null) {
                        WelfareCouponRecord welfareCouponRecord = welfareCouponRecordService.selectWelfareCouponRecordById(orderConsumeRecord.getCouponRecordId());
                        if (welfareCouponRecord == null) {
                            throw new RuntimeException("优惠券不存在，请选择正确的核销方式");
                        }
                        WelfareCoupon welfareCoupon = welfareCouponService.selectWelfareCouponById(welfareCouponRecord.getCouponId());

                        //判断优惠券是否需要付款
                        if (welfareCoupon.getChargeType() == 2) {

                            if (orderConsumeRecord.getAmount() == null) {
                                orderConsumeRecord.setAmount(welfareCoupon.getPrice());
                            }

                            //如果是餐饮项目，金额=金额*人数
                            if ("1".equals(orderConsumeRecord.getServeType()) && orderConsumeRecord.getNum() != null) {
                                orderConsumeRecord.setAmount(orderConsumeRecord.getAmount().multiply(new BigDecimal(orderConsumeRecord.getNum())));
                            }

                            //扣减余额
                            synchronized (this) {
                                int i = memberUserInfoService.updateMemberBalance(memberUserInfo.getId(), orderConsumeRecord.getAmount());
                                if (i < 1) {
                                    throw new RuntimeException("余额不足，请先充值！");
                                }
                            }

                            if (orderConsumeRecord.getCardType() == 2){
                                memberSubCardInfoService.updateMemberSubTotalAmount(orderConsumeRecord.getMemberId(),orderConsumeRecord.getAmount());
                            }
                        }

                        //更新优惠券状态
                        welfareCouponRecord = new WelfareCouponRecord();
                        welfareCouponRecord.setId(orderConsumeRecord.getCouponRecordId());
                        welfareCouponRecord.setUseTime(new Date());
                        welfareCouponRecord.setStatus(1);
                        orderConsumeRecord.setServeType(welfareCoupon.getServeType());
                        orderConsumeRecord.setServeName(welfareCoupon.getName());
                        welfareCouponRecordService.updateWelfareCouponRecord(welfareCouponRecord);
                    }
                    break;
                default: {
                    throw new RuntimeException("不支持的支付类型");
                }


            }

            //主卡余额
            memberUserInfo = memberUserInfoService.selectMemberUserInfoById(memberUserInfo.getId());
            orderConsumeRecord.setBalance(memberUserInfo.getBalance());

            //非核销则生成订单号
            if (StringUtils.isEmpty(orderConsumeRecord.getOrderNum())){
                orderConsumeRecord.setOrderNum(UUID.generateOrderNumber());
            }
            orderConsumeRecord.setCreateBy(SecurityUtils.getUsername());
            orderConsumeRecord.setCreateTime(DateUtils.getNowDate());
            return orderConsumeRecordMapper.insertOrderConsumeRecord(orderConsumeRecord);
        }catch (Exception e){
            error(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 修改消费订单
     *
     * @param orderConsumeRecord 消费订单
     * @return 结果
     */
    @Override
    public int updateOrderConsumeRecord(OrderConsumeRecord orderConsumeRecord)
    {
        orderConsumeRecord.setUpdateTime(DateUtils.getNowDate());
        return orderConsumeRecordMapper.updateOrderConsumeRecord(orderConsumeRecord);
    }

    /**
     * 批量删除消费订单
     *
     * @param ids 需要删除的消费订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderConsumeRecordByIds(Long[] ids)
    {
        return orderConsumeRecordMapper.deleteOrderConsumeRecordByIds(ids);
    }

    /**
     * 删除消费订单信息
     *
     * @param id 消费订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderConsumeRecordById(Long id)
    {
        return orderConsumeRecordMapper.deleteOrderConsumeRecordById(id);
    }

    @Override
    public Integer selectServeCount(Long serveId) {
        return orderConsumeRecordMapper.selectServeCount(serveId);
    }

    @Override
    public List<OrderUniVo> selectOrderUniList(Long memberId,Integer cardType) {
        return orderConsumeRecordMapper.selectOrderUniList(memberId,cardType);
    }

    @Override
    public List<OrderUniVo> selectOrderUniSubList(Long memberId, Integer cardType) {
        return orderConsumeRecordMapper.selectOrderUniSubList(memberId,cardType);
    }
}
